﻿// Apache-2.0 License
// Copyright (c) 2021-2022 朱飞龙
// 电话/微信：18706708563  QQ群：136192142

using Admin.NET.Application.Util.Extension;
using Admin.NET.Interface.Kingdee.Util.Extension;
using Radius.NET.Interface.Kingdee.Entity;
using Radius.NET.Interface.Kingdee.Service.StockWareModule.Dto;
using static Radius.NET.Interface.Kingdee.Service.Production.KindeeIssueDto;
using static Radius.NET.Interface.Kingdee.Service.StockWareModule.Dto.KindeeStockWareDto;

namespace Radius.NET.Interface.Kingdee.Service.StockWareModule;

/// <summary>
/// 库存模块接口
/// </summary>
[ApiDescriptionSettings(KingdeeConfigConst.GroupName, Order = 002)]
public class StockQtckdService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<InventoryEvidence> evidenveRespository;

    private readonly KingdeeUtil _kingdeeUtil;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="_evidenveRespository"></param>
    /// <param name="kingdeeUtil"></param>
    public StockQtckdService(SqlSugarRepository<InventoryEvidence> _evidenveRespository,
        KingdeeUtil kingdeeUtil)
    {
        evidenveRespository = _evidenveRespository;
        _kingdeeUtil = kingdeeUtil;
    }

    #region 其他出库单保存同步到云星空
    /// <summary>
    /// 其他出库单保存同步到云星空
    /// </summary>
    /// <returns></returns>
    [HttpPost("/kindeeIcloud/stockwaremodule/qtchd/save/{cid}"), AllowAnonymous]
    public async Task<object> SyncToStkQtCk(int cid, string EviNum)
    {
        var KingdeeUtil = await _kingdeeUtil.GetClient("kindeeIcloud_stockwaremodule_qtchd_save");
        if (string.IsNullOrEmpty(EviNum))
            throw Oops.Oh(errorMessage: "单号不能为空！");

        //获取包材出库单数据
        var iqckdItem = await evidenveRespository.AsQueryable()
            .Includes(x => x.FG_InvDetail, inv => inv.FG_Inventory)
            .Where(x => x.Evidence_Number.Equals(EviNum) && x._cid == cid)
            .FirstAsync();

        if (iqckdItem is null)
            throw Oops.Bah("仓库单据记录不存在！");

        var data = KindeeStockWareDto.BuildQtckJsonData(iqckdItem);

        TP.Wrapper("云星空其他出库单保存", "其他出库单保存生成其他出库单",
            $"##本地json## {JsonConvert.SerializeObject(iqckdItem)}",
            $"##云星空json## {JsonConvert.SerializeObject(data)}").LogInformation();

        return KingdeeUtil.Save("STK_MisDelivery", data);
    }
    #endregion

    #region 仓库单据保存同步生产领料单保存无关联
    /// <summary>
    /// 仓库单据保存生产领料单保存无关联
    /// </summary>
    /// <returns></returns>
    [HttpPost("/kindeeIcloud/stockwaremodule/evidence/sclld/notrel/save/{cid}"), AllowAnonymous]
    public async Task<object> SyncToScllDNotRelation(int cid, string EviNum)
    {
        var KingdeeUtil = await _kingdeeUtil.GetClient("kindeeIcloud_stockwaremodule_qtchd_notrel_save");
        if (string.IsNullOrEmpty(EviNum))
            throw Oops.Oh(errorMessage: "单号不能为空！");

        //获取入库单数据
        var iqckdItem = await evidenveRespository.AsQueryable()
            .Includes(x => x.FG_InvDetail, z => z.FG_Inventory)
            .Where(x => x.Evidence_Number.Equals(EviNum) && x._cid == cid)
            .FirstAsync();

        if (iqckdItem is null)
            throw Oops.Bah("出库单记录不存在！");

        JsonConvert.SerializeObject(iqckdItem).LogInformation();

        var data = KindeeStockWareDto.BuildSclldJsonData(iqckdItem);

        TP.Wrapper("云星空生产领料单保存", "仓库单据保存生成生产领料单",
        $"##本地json## {JsonConvert.SerializeObject(iqckdItem)}",
        $"##云星空json## {JsonConvert.SerializeObject(data)}").LogInformation();

        return KingdeeUtil.Save("PRD_PickMtrl", data);
    }
    #endregion

    #region 发货通知单下推成品出库单
    /// <summary>
    /// 发货通知单下推成品出库单
    /// </summary>
    /// <returns></returns>
    [HttpPost("/kindeeIcloud/stockwaremodule/cpck/push/{cid}"), AllowAnonymous]
    public async Task<object> SyncToFhtzdPushCpck(int cid, string EviNum)
    {
        var KingdeeUtil = await _kingdeeUtil.GetClient("kindeeIcloud_stockwaremodule_cpck_push");
        if (string.IsNullOrEmpty(EviNum))
            throw Oops.Oh(errorMessage: "单号不能为空！");

        var data = new
        {
            Ids = "",
            Numbers = EviNum,
            EntryIds = "",
            RuleId = "38e62a2f-557f-48e4-b60c-880e7e14aca7",
            TargetBillTypeId = "",
            TargetOrgId = 0,
            TargetFormId = "SAL_OUTSTOCK",
            IsEnableDefaultRule = "true",
            IsDraftWhenSaveFail = "false",
            CustomParams = new { }
        };
        var obj = KingdeeUtil.Push("SAL_DELIVERYNOTICE", data);
        return obj;
    }
    #endregion

    #region 成品出库单保存同步销售出库单
    /// <summary>
    /// 成品出库单保存同步销售出库单
    /// </summary>
    /// <returns></returns>
    [HttpPost("/kindeeIcloud/stockwaremodule/cpck/save/{cid}"), AllowAnonymous]
    public async Task<object> SyncToCpckSave(int cid, string EviNum)
    {
        var KingdeeUtil = await _kingdeeUtil.GetClient("kindeeIcloud_stockwaremodule_cpck_save");
        if (string.IsNullOrEmpty(EviNum))
            throw Oops.Oh(errorMessage: "单号不能为空！");
        //获取单据数据
        var eviItem = await evidenveRespository.AsQueryable()
            .Includes(x => x.FG_InvDetail, z => z.FG_Inventory)
            .Where(x => x.Evidence_Number.Equals(EviNum) && x._cid == cid)
            .FirstAsync();

        if (eviItem is null)
            throw Oops.Bah("单据记录不存在！");

        JsonConvert.SerializeObject(eviItem).LogInformation();
        string[] inventoryIds = eviItem.FG_InvDetail.Select(x => $"'{x.Inventory_ID}'").Distinct().ToArray();
        
        var data = KindeeStockWareDto.BuildxsckdJsonData(eviItem, QueryFHTZDByNumber(KingdeeUtil, eviItem.ReasonID), GetInventoryByNumber(KingdeeUtil, inventoryIds));

        TP.Wrapper("云星空组销售出库单保存", "成品出库单保存生成销售出库单",
        $"##本地json## {JsonConvert.SerializeObject(eviItem)}",
        $"##云星空json## {JsonConvert.SerializeObject(data)}").LogInformation();

        return KingdeeUtil.Save("SAL_OUTSTOCK", data);
    }
    #endregion

    #region 退货通知单下推成品退货单
    /// <summary>
    /// 退货通知单下推成品退货单
    /// </summary>
    /// <returns></returns>
    [HttpPost("/kindeeIcloud/stockwaremodule/cpth/push/{cid}"), AllowAnonymous]
    public async Task<object> SyncToThtzdPushCpth(int cid, string EviNum)
    {
        var KingdeeUtil = await _kingdeeUtil.GetClient("kindeeIcloud_stockwaremodule_cpth_push");
        if (string.IsNullOrEmpty(EviNum))
            throw Oops.Oh(errorMessage: "单号不能为空！");

        var data = new
        {
            Ids = "",
            Numbers = EviNum,
            EntryIds = "",
            RuleId = "OutStock-SalReturnNotice",
            TargetBillTypeId = "",
            TargetOrgId = 0,
            TargetFormId = "SAL_RETURNSTOCK",
            IsEnableDefaultRule = "true",
            IsDraftWhenSaveFail = "false",
            CustomParams = new { }
        };
        var obj = KingdeeUtil.Push("SAL_RETURNNOTICE", data);
        return obj;
    }
    #endregion

    #region 发套料同步直接调拨单
    /// <summary>
    /// 发套料同步直接调拨单
    /// </summary>
    /// <param name="cid"></param>
    /// <param name="EviNum"></param>
    /// <returns></returns>
    [HttpPost("/kindeeIcloud/stockwaremodule/qtdb/save/{cid}"), AllowAnonymous]
    public async Task<object> PgroToTransferDirect(int cid, string EviNum)
    {
        //获取同步金蝶云星空客户端
        var KingdeeUtil = await _kingdeeUtil.GetClient("kindeeIcloud_stockwaremodule_pgrototransferdirect_save");
        if (string.IsNullOrEmpty(EviNum))
            throw Oops.Oh(errorMessage: "单号不能为空！");

        //获取发套料单数据
        var pgroItem = await evidenveRespository.AsQueryable()
            .Includes(x => x.FG_InvDetail, z => z.FG_Inventory)
            .Where(x => x.Evidence_Number.Equals(EviNum) && x._cid == cid)
            .FirstAsync();

        if (pgroItem is null)
            throw Oops.Bah("发套料记录不存在！");

        JsonConvert.SerializeObject(pgroItem).LogInformation();
        string[] inventoryIds = pgroItem.FG_InvDetail.Select(x => $"'{x.Inventory_ID}'").Distinct().ToArray();

        var data = new STK_TransferDirect().BuildData(pgroItem, GetInventoryByNumber(KingdeeUtil, inventoryIds));

        TP.Wrapper("云星空直接调拨单保存", "发套料单据保存生成直接调拨单",
        $"##本地json## {JsonConvert.SerializeObject(pgroItem)}",
        $"##云星空json## {JsonConvert.SerializeObject(data)}")
            .LogInformation();

        return KingdeeUtil.Save("STK_TransferDirect", data);
    }
    #endregion

    #region 读取即时库存
    /// <summary>
    /// 读取即时库存
    /// </summary>
    /// <param name="cid"></param>
    /// <returns></returns>
    [HttpPost("/kindeeIcloud/stockwaremodule/jskc/list/{cid}"), AllowAnonymous]
    public async Task<List<STK_Inventory_Dto>> GetYxkSTK_Inventory(int cid)
    {
        var KingdeeUtil = await _kingdeeUtil.GetClient("kindeeIcloud_stockwaremodule_jskc_list");
        string FilterString = $"FStockOrgId.FNumber = '{KingdeeConfigConst.ORGID}' and FBaseQty > 0";
        var list = KingdeeUtil.Query<STK_Inventory_Dto>(KingdeeFormConst.STK_Inventory, FilterString);
        return list;
    }
    #endregion

    #region 成品组装拆卸单同步组装拆卸单
    /// <summary>
    /// 成品组装拆卸单同步组装拆卸单
    /// </summary>
    /// <param name="cid"></param>
    /// <param name="EviNum"></param>
    /// <returns></returns>
    [HttpPost("/kindeeIcloud/stockwaremodule/zzcxd/save/{cid}"), AllowAnonymous]
    public async Task<object> FgdSysToStkAssembledApp(int cid, string EviNum)
    {
        //获取同步金蝶云星空客户端
        var KingdeeUtil = await _kingdeeUtil.GetClient("kindeeIcloud_stockwaremodule_StkAssembledApp_save");
        if (string.IsNullOrEmpty(EviNum))
            throw Oops.Oh(errorMessage: "单号不能为空！");

        //获取组装拆卸单数据
        var eviItem = await evidenveRespository.AsQueryable()
            .Includes(x => x.FG_InvDetail, z => z.FG_Inventory)
            .Where(x => x.Evidence_Number.Equals(EviNum) && x._cid == cid)
            .FirstAsync();

        if (eviItem is null)
            throw Oops.Bah("单据记录不存在！");

        JsonConvert.SerializeObject(eviItem).LogInformation();

        var data = KindeeStockWareDto.BuildzzcxdJsonData(eviItem);

        TP.Wrapper("云星空组装拆卸单保存", "成品组装拆卸单保存生成组装拆卸单",
        $"##本地json## {JsonConvert.SerializeObject(eviItem)}",
        $"##云星空json## {JsonConvert.SerializeObject(data)}").LogInformation();

        return KingdeeUtil.Save("STK_AssembledApp", data);
    }
    #endregion

    #region 根据发货通知单单号查询金蝶发货通知单
    /// <summary>
    /// 根据发货通知单单号查询金蝶发货通知单
    /// </summary>
    /// <param name="kingdeeUtil"></param>
    /// <param name="number"></param>
    /// <returns></returns>
    [NonAction]
    public List<SAL_DELIVERYNOTICE_Dto> QueryFHTZDByNumber(KingdeeUtil kingdeeUtil, string number)
    {
        var list = kingdeeUtil.Query<SAL_DELIVERYNOTICE_Dto>(KingdeeFormConst.SAL_DELIVERYNOTICE, $"FBillNo = '{number}'");
        if (list.Count == 0)
            throw Oops.Bah("金蝶收料通知单记录不存在！");

        return list;
    }
    #endregion

    #region 根据物料编码查询云星空物料档案
    /// <summary>
    /// 根据物料编码查询云星空物料档案
    /// </summary>
    /// <param name="kingdeeUtil"></param>
    /// <param name="Fnumbers"></param>
    /// <returns></returns>
    private Dictionary<string, BD_MATERIAL_Dto> GetInventoryByNumber(KingdeeUtil kingdeeUtil, string[] Fnumbers)
    {
        string FilterString = $"FNumber in ({string.Join(",", Fnumbers)})";
        var list2 = kingdeeUtil.Query<BD_MATERIAL_Dto>("BD_MATERIAL", FilterString);
        Dictionary<string, BD_MATERIAL_Dto> dicts = new Dictionary<string, BD_MATERIAL_Dto>();

        foreach (var item in list2)
        {
            if (!dicts.ContainsKey(item.FNumber))
            {
                var obj = new BD_MATERIAL_Dto()
                {
                    FAuxUnitID__FNumber = item.FAuxUnitID__FNumber.IsNullOrEmpty() ? "" : item.FAuxUnitID__FNumber,
                    FBaseUnitId__FNumber = item.FBaseUnitId__FNumber.IsNullOrEmpty() ? "" : item.FBaseUnitId__FNumber,
                    FStoreUnitID__FNumber = item.FStoreUnitID__FNumber.IsNullOrEmpty() ? "" : item.FStoreUnitID__FNumber,
                };
                dicts.Add(item.FNumber, obj);
            }
        }
        JSON.Serialize(dicts).LogInformation();
        return dicts;
    }
    #endregion

}
